package cn.xuqiudong.demo.oss.download;

import cn.xuqiudong.demo.oss.base.BaseDemo;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.LocalTime;

/**
 * 描述:
 * @author Vic.xu
 * @since 2023-01-10 16:54
 */

@Controller
public class DownloadController extends BaseDemo {


    @RequestMapping("download")
    public void download(HttpServletResponse response) throws IOException {
        String objectName = "12889/eed478d205c845959ea147a1e60d252f-test20230110.docx";
        InputStream in = getInputStream(objectName);
        String contentType = "application/octet-stream";

        response.setContentType(contentType);
        String filename = LocalTime.now() + "test20230110.docx";
        filename = new String(filename.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);

        response.setHeader("Content-disposition", "attachment; filename=\"" + filename + "\"");
        FileCopyUtils.copy(in, response.getOutputStream());
    }


    private InputStream getInputStream(String objectName) {
        OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        boolean found = oss.doesObjectExist(bucketName, objectName);
        if (!found) {
            System.out.println(objectName + "文件不存在");
            return null;
        }
        try {
            OSSObject object = oss.getObject(bucketName, objectName);
            return object.getObjectContent();

        } catch (Exception e) {
            return null;
        } finally {
            oss.shutdown();
        }
    }
}
